<?php

namespace app\common\model\goods;

use app\common\model\order\Order;
use think\Db;
use think\Model;


class Review extends Model
{





    // 表名
    protected $name = 'goods_review';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'images_array',
    ];

    public function getImagesArrayAttr($value, $data)
    {
        if ($data['images']) {
            $arr = explode(',', $data['images']);
            foreach ($arr as &$v) {
                $v = cdnurl($v, true);
            }
            return $arr;
        }
        return [];
    }
    public function goods()
    {
        return $this->belongsTo('app\common\model\goods\Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function order()
    {
        return $this->belongsTo('app\common\model\order\Order', 'order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function addReview($array, $user_id)
    {
        extract($array);
        Db::startTrans();
        try {
            foreach ($data as &$v) {
                $v['user_id'] = $user_id;
            }
            $this->allowField(true)->saveAll($data);
            $order = new Order();
            $order->save(['status' => 4], ['id' => $order_id]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
        return true;
    }
}
